package com.study.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicket
{
    public static void main(String[] args)
    {
//        Ticket ticket = new Ticket();
        Ticket1 ticket = new Ticket1();
        new Thread(() -> {
            for (int i = 0; i < 40; i++)
            {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++)
            {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++)
            {
                ticket.sale();
            }
        }, "C").start();
    }
}

class Ticket
{
    private int number = 30;

    public synchronized void sale()
    {
        if (number > 0)
        {
            System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票，剩余：" + number);
        }
    }
}

class Ticket1
{
    private int number = 30;
    Lock lock = new ReentrantLock();

    public void sale()
    {
        lock.lock();
        try
        {
            if (number > 0)
            {
                System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票，剩余：" + number);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            lock.unlock();
        }
    }
}
